package tij4.concurrent.source;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Accessor implements Runnable {
    private final int id;

    public Accessor(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            ThreadLocalVariableHolder.increment();
            System.out.println(this);
            Thread.yield();
//            try {
//                TimeUnit.SECONDS.sleep(1);
//            }catch (InterruptedException e){
//
//            }
        }
    }

    @Override
    public String toString() {
        return "#" + id + ": "  + ThreadLocalVariableHolder.get();
    }
}

public class ThreadLocalVariableHolder {
    private static ThreadLocal<Integer> value = new ThreadLocal<Integer>(){
            private Random random = new Random(47);
            protected synchronized Integer initialValue() {
                return random.nextInt(10000);
            }
        };

    public static void increment() {
        value.set(value.get() + 1);
    }
    public static int get() {
        return value.get();
    }

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        /*
            执行的结果不会跳出for循环
         */
        for (int i = 0; i <= 4; i++) {
            executorService.execute(new Accessor(i));
            System.out.println("================="+i);
        }
        System.out.println("+++++++++++++++++++++++++++++++++++++");
        TimeUnit.SECONDS.sleep(3);
        System.out.println("-------------------------------------------");
        executorService.shutdownNow();
    }

}
